/*
 *  Filename: base64.c
 *  Function: base64 encode
 *  Created: 2017-05-03
 *  Version: 1.0
 *  Authror: Bin
 */

#include "base64.h"
#include <stdlib.h>

static const char base64_chars[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";

char* base64_encode(const unsigned char *data, int len)
{
    char *ret;
    int ret_len;

    // allocate space for return value
    if (len % 3 == 0)
        ret_len = len / 3 * 4;
    else
        ret_len = len /3 * 4 + 4;

    ret = malloc(ret_len + 1);

    if (ret) {
        char *p = ret;
        int i = 0, j = 0;
        unsigned char char_array_3[3];
        unsigned char char_array_4[4];

        while (len--) {
            char_array_3[i++] = *data++;
            if (i == 3) {
                char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
                char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
                char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
                char_array_4[3] = char_array_3[2] & 0x3f;

                for (i = 0; i < 4; i++)
                    *p++ = base64_chars[char_array_4[i]];

                i = 0;
            }
        }

        if (i) {
            for (j = i; j < 3; j++)
                char_array_3[i] = '\0';

            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for (j = 0; j < i + 1; j++)
                *p++ = base64_chars[char_array_4[j]];

            while (i++ < 3)
                *p++ = '=';
        }

        *p = '\0';
    }

    return ret;
}
